package me.caofeng.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import me.caofeng.dao.AddressMapper;
import me.caofeng.dao.OrderMapper;
import me.caofeng.enums.OrderStatus;
import me.caofeng.enums.ResponseCode;
import me.caofeng.enums.Role;
import me.caofeng.pojo.*;
import me.caofeng.service.api.ICartService;
import me.caofeng.service.api.IOrderService;
import me.caofeng.util.CheckUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.print.DocFlavor;
import java.sql.SQLException;
import java.util.List;


/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.service
 * @Description:
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-07-01 21:02
 * @Version: V1.0
 */
@Service
@Transactional
public class OrderService implements IOrderService {
    private static Logger LOGGER = LogManager.getLogger(OrderService.class);

    @Autowired
    private ICartService cartService;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Response<Order> buildOrderFromCart(String userId, Integer addressId) throws SQLException {
        LOGGER.info(userId + " " + addressId);
        // 从购物车中获取已选的商品
        Response cartsResponse = cartService.getCarts(userId);

        if (!cartsResponse.isSuccess()) {
            return cartsResponse;
        }

        //检查地址是否存在
        Address address = addressMapper.getAddress(addressId, userId);

        LOGGER.info(address);
        if (null == address) {
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "地址不存在", null);
        }

        Carts carts = (Carts) cartsResponse.getData();

        //将购物车中的商品转为订单信息
        Order order = new Order(carts, userId, addressId);

        // 保存订单信息
        int orderRow = orderMapper.addOrder(order);
        int orderItemRow = orderMapper.addOrderItem(order.getItems());

        if (orderRow != 1 || orderItemRow < 1) {
            return Response.response(ResponseCode.ERROR, "生成订单失败", null);
        }

        //清空购物车
        if (!cartService.clearCart(userId).isSuccess()) {
            throw new SQLException("清空购物车失败");
        }

        //设置收获地址
        order.setAddress(address);
        return Response.response(ResponseCode.SUCCESS, "生成订单成功", order);
    }

    @Override
    public Response<Order> buildOrderFromProduct(String userId, Integer addressId, Integer productId, Integer count) {
        LOGGER.info(userId + " " + addressId + " " + productId + " " + count);
        //todo 组装订单信息

        //todo  保存订单信息
        return Response.response(ResponseCode.SUCCESS, "生成订单成功", null);
    }

    @Override
    public Response<Order> getOrderDetail(String userId, String orderId) {
        Order order = orderMapper.getOrder(userId, orderId);
        if (null == order) {
            return Response.response(ResponseCode.EMPTY, "订单不存在 ", null);
        }
        userId = null == userId ? order.getUserId() : userId ;
        order.setItems(orderMapper.getOrderItems(userId, orderId));
        Address address = addressMapper.getAddress(order.getAddressId(), userId);
        order.setAddress(address);
        //todo 获取快递信息
        return Response.response(ResponseCode.SUCCESS, "获取订单详情成功", order);
    }

    @Override
    public Response<PageInfo<List<Order>>> getOrdersAsPageInfo(String userId, OrderStatus status, Role role, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orders = orderMapper.getOrders(userId, status, role, null);
        PageInfo<List<Order>> pageInfo = new PageInfo(orders);
        buildOrders(orders,userId);
        return Response.response(ResponseCode.SUCCESS, "获取订单列表成功", pageInfo);
    }

    @Override
    public Response<Page<List<Order>>> getOrders(String userId, OrderStatus status, Role role, Integer pageNum, Integer pageSize) {
        Page<List<Order>> page = new Page<>(pageNum, pageSize);
        List<Order> orders = orderMapper.getOrders(userId, status, role, page);

        if (orders.size() == 0) {
            return Response.response(ResponseCode.EMPTY, "暂时没有订单", null);
        }

        buildOrders(orders,userId);
        page.setPageNumber(pageNum);
        page.setList(orders);
        page.setSize(orders.size());
        return Response.response(ResponseCode.SUCCESS, "获取订单成功", page);
    }

    @Override
    public Response cancelOrder(String userId, String orderId) {
        int row = orderMapper.cancelOrder(userId,orderId);
        if (row != 1){
            return Response.response(ResponseCode.ERROR,"取消订单失败",null);
        }
        return Response.response(ResponseCode.SUCCESS,"取消订单成功",null);
    }

    @Override
    public Response deleteOrder(String userId, String orderId) {
        int row = orderMapper.deleteOrder(userId,orderId);
        if (row != 1){
            return Response.response(ResponseCode.ERROR,"删除订单失败",null);
        }
        return Response.response(ResponseCode.SUCCESS,"删除订单",null);
    }

    @Override
    public Response sendPost(String orderId, String postId) {
        //验证订单是否存在,以及是否已经支付
        Order order = orderMapper.getOrderUserAndAddress(orderId);
        if (null == order || CheckUtil.isEmpty(order.getUserId()) || order.getAddressId() <= 0){
            return Response.response(ResponseCode.ILLEGAL_ARGUMENT,"订单未支付或不存在",null);
        }
        //todo 向物流平台确认物流单号正确性

        //获取收货人信息
        Address address = addressMapper.getAddress(order.getAddressId(),order.getUserId());

        // 组装物流信息
        PostInfo postInfo = new PostInfo(orderId,postId,"物流公司名字");
        postInfo.setUserId(order.getUserId());
        postInfo.setGoal(address.addressInfo());

        //更新订单状态
        int statusRow = orderMapper.updatePostStatus(orderId,OrderStatus.SEND)  ;
        //添加物流信息
        int postInfoRow = orderMapper.addPostInfo(postInfo);
        if ( statusRow != postInfoRow ){
           LOGGER.error("发货失败");
           return Response.response(ResponseCode.ERROR,"发货失败",null);
        }
        return Response.response(ResponseCode.SUCCESS,"发货成功",postInfo);
    }

    @Override
    public Response signOrder(String orderId, String userId) {
        // todo 修改订单状态
        int statusRow = orderMapper.signOrder(orderId,userId,OrderStatus.END);

        if (statusRow != 1){
            return Response.response(ResponseCode.ERROR,"确认收货失败",null);
        }

        // todo 获取物流详情
        PostInfo postInfo = new PostInfo(orderId,userId);
        postInfo.setDetail("物流详情");
        // todo 修改物流信息
        int row = orderMapper.updatePostInfo(postInfo);
        if (row != 1){
            return Response.response(ResponseCode.ERROR,"确认是收货失败",null);
        }
        return Response.response(ResponseCode.SUCCESS,"确认收货成功",null);
    }

    private void buildOrders(List<Order> orders,String userId) {
        //todo 获取快递信息
        orders.forEach(order -> {
            String user = null == userId ? order.getUserId() : userId;
            Address address = addressMapper.getAddress(order.getAddressId(), user);
            List<OrderItem> items = orderMapper.getOrderItems(user, order.getOrderId());
            order.setAddress(address);
            order.setItems(items);
        });
    }
}
